from umqtt.simple import MQTTClient
from machine import Timer
from config import Config
import gc

class mqtt_lient:
	def __init__(self, led):
		self._led = led
		self._check_message_timer = Timer(0)

		self._client = MQTTClient(
			Config.MQTT_CLIENT_ID,
			Config.MQTT_HOST,
			Config.MQTT_HOST_PORT,
			Config.MQTT_USERNAME,
			Config.MQTT_PASSWORD,
		)

	def _client_topic_cb(self, topic, msg):
		print("\n- received topic: %s\n- message: %s" % (topic, msg))

		if (msg == b'led_on'):
			self._led.value(0)
		elif (msg == b'led_off'):
			self._led.value(1)
		else:
			self._led.value(not self._led.value())

		gc.collect()

	def _check_message_cb(self, timer):
		try:
			self._client.check_msg()
		except OSError as e:
			if (str(e) == "-1"):
				self._client.disconnect()
				self._check_message_timer.deinit()

				self.start()
			else:
				print(e)

		gc.collect()

	def start(self):
		self._client.set_callback(self._client_topic_cb)
		self._client.connect()
		self._client.subscribe(Config.MQTT_TOPIC)

		print("Connected to %s\nSubscribed topic %s\n" % (Config.MQTT_HOST, Config.MQTT_TOPIC))

		self._check_message_timer.init(
			mode=Timer.PERIODIC,
			period=100,
			callback=self._check_message_cb
		)

		gc.collect()
